package com.tz.advice;

import com.tz.service.AccountService;
import com.tz.service.AccountServiceImpl;
import com.tz.util.HibernateUtil;
import com.tz.util.MyAcUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.tz.util.MyThreadLocal;
import org.springframework.stereotype.Component;

/**
 * Created by user on 2016/10/10.
 */
@Component
@Aspect
public class MyTxAdvice {

    private SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

    //@Around("execution(public * com.tz.service.AccountServiceImpl.transfer(..))")
    Object around(ProceedingJoinPoint pjp){
        Object result=null;

        Session session = sessionFactory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            MyThreadLocal.set(session);
            result = pjp.proceed();//放行请求,相当于箭头2
            tx.commit();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            if (tx!=null){
                tx.rollback();
            }
        }
        return result;
    }
}
